<template>
	<page-header-wrapper>
		<template slot="extra">
			<back-button />
		</template>
		<a-spin :spinning="loading">
			<a-card :bordered="false">
				<a-descriptions title="订单信息">
					<a-descriptions-item label="衣服数量">{{ cart.length }}</a-descriptions-item>
					<a-descriptions-item v-if="order.activity_id" label="活动名称"><span
							class="primary-color">{{ order.activity_name }}</span>
					</a-descriptions-item>
					<!-- <a-descriptions-item v-else></a-descriptions-item> -->
					<!-- <a-descriptions-item></a-descriptions-item> -->
					<a-descriptions-item label="订单状态">
						<span class="primary-color">{{ order | statusFilter }}</span>
					</a-descriptions-item>
					<a-descriptions-item label="价格">{{ '￥' + order.price }}</a-descriptions-item>
					<!-- <a-descriptions-item></a-descriptions-item> -->
					<a-descriptions-item label="订单编号">{{ order.out_trade_no }}</a-descriptions-item>
					<a-descriptions-item label="封签码">{{ order.seal_code }}</a-descriptions-item>
					<!-- <a-descriptions-item label="使用年卡次数">{{ order.year_card_num }}</a-descriptions-item> -->
					<a-descriptions-item label="是否使用优惠券">{{
            order.card_discount === 2 ? '是' : '否'
          }}</a-descriptions-item>
					<a-descriptions-item label="使用会员身份">{{
            order.is_vip_discount === 1 ? '是' : '否'
          }}</a-descriptions-item>
					<a-descriptions-item label="是否加急">{{ order.is_urgent === 1 ? '是' : '否' }}</a-descriptions-item>
					<a-descriptions-item label="收衣配送费">{{ order.take_express_price || '无' }}</a-descriptions-item>
					<a-descriptions-item label="送衣配送费">{{ order.send_express_price || '无' }}</a-descriptions-item>
					<!-- <a-descriptions-item></a-descriptions-item> -->
					<a-descriptions-item label="收衣接单人">{{ order.take_worker }}</a-descriptions-item>
					<a-descriptions-item label="送衣接单人">{{ order.send_worker }}</a-descriptions-item>
					<!-- <a-descriptions-item></a-descriptions-item> -->
					<a-descriptions-item label="取衣联系人">{{
            `${order.take_name || ''} ${order.take_mobile || ''}`
          }}</a-descriptions-item>
					<a-descriptions-item label="取衣地址">{{ order.take_address }}</a-descriptions-item>
					<!-- <a-descriptions-item></a-descriptions-item> -->
					<a-descriptions-item label="送衣联系人">{{
            `${order.send_name || ''} ${order.send_mobile || ''}`
          }}</a-descriptions-item>
					<a-descriptions-item label="送衣地址">{{ order.send_address }}</a-descriptions-item>
					<!-- <a-descriptions-item></a-descriptions-item> -->
					<a-descriptions-item label="支付方式">{{ order.pay_type | payTypeFilter }}</a-descriptions-item>
					<a-descriptions-item label="订单创建时间">{{ order.ctime }}</a-descriptions-item>
					<a-descriptions-item label="乐管家门店订单">{{
            order.steward_user_id != 0 ? '销售订单' : order.share_user_id != 0 ? '分享订单' : '否'
          }}</a-descriptions-item>
					  <a-descriptions-item label="备注">{{order.remark}}</a-descriptions-item>
					  <a-descriptions-item label="是否卡兑换">{{order.ecard_id > 0 ?'是':'否'}}</a-descriptions-item>
				</a-descriptions>
				<a-divider style="margin-bottom: 32px" />
				<a-descriptions title="京东物流" v-if="order.express_status == 1">
					<a-descriptions-item label="订单号">{{ express.data.waybillCode }}</a-descriptions-item>
				</a-descriptions>
				<a-divider style="margin-bottom: 32px" v-if="order.express_status == 1" />
				<div class="table-title-container">
					<div class="table-title">衣物列表</div>
					<div class="imgs">
						<img :src="item" v-for="(item, index) in order.img_url" :key="index" @click="largeimg(item)" />
					</div>
					<template v-if="showimg">
						<div class="imgpage">
							<img :src="lookimg" alt="" @click="showimg = false" />
						</div>
					</template>
					<!-- <template v-if="$route.query.seal_code && isActvityOrder"> -->
					<template v-if="isActvityOrder">
						<a-button type="primary" @click="handleAdd(0)" v-if="!order.clothes_num">添加衣物</a-button>
						<a-button type="primary" @click="handleAdd(1)" v-else>重新添加</a-button>
					</template>
				</div>
				<a-table style="margin-bottom: 24px" row-key="id" :columns="columns" :dataSource="cart"
					:pagination="false">
					<template slot="img_url" slot-scope="text">
						<a-avatar shape="square" :size="64" icon="skin" :src="text" />
					</template>
					<template slot="kinds_status" slot-scope="kinds_status">
						<a-tag
							:color="kinds_status == 1 ? 'blue' : 'red'">{{ kinds_status | kindsStatusFilter }}</a-tag>
					</template>
					<template slot="is_protect_price" slot-scope="is_protect_price">
						<a-tag
							:color="is_protect_price > 0 ? 'blue' : 'red'">{{ is_protect_price > 0 ? '是' : '否' }}</a-tag>
					</template>
					<template slot="pack_price" slot-scope="pack_price">
						<a-tag :color="pack_price > 0 ? 'blue' : 'red'">{{ pack_price > 0 ? '是' : '否' }}</a-tag>
					</template>
					<template slot="is_take" slot-scope="is_take">
						<a-badge :status="is_take == 5 ? 'success' : 'processing'" :text="is_take | isTakeFilter"
							slot="status" />
					</template>
					<!--v-if="order.seal_code"-->
					<span slot="action" slot-scope="text, record">
						<template>
							<a v-if="order.send_worker_from != 'express'" @click="handleSplit(record)">备注/拆分</a>
						</template>
					</span>
				</a-table>
				<div class="print-container">
					<div class="print-item-wrap" v-for="item in printList" :key="item.id">
						<!-- <div class="print-item" v-if='item.is_remark==1 && item.is_take==4'> -->
						<div class="print-item">
							<div class="print-left">
								<div class="print-img">
									<barcode :value="item.bar_code" :width="1.5" :height="50" :fontSize="12"
										fontOptions="Arial" :text="item.bar_code">条形码生成失败</barcode>
								</div>
								<!-- <div class="print-code">{{ item.bar_code }}</div> -->
							</div>
							<div class="print-right">
								<div class="print-info">
									<span class="print-info-item">
										店名:{{ store.name }}
										<template v-if="item.kinds_status == 1">（奢侈品）</template>
										<template v-if="order.is_urgent > 0">（加急）</template>
										<template v-if="item.pack_price > 0">（包装）</template>
										<template>{{ getUserCard() }}</template>
									</span>
								</div>
								<div class="print-info">
									<span class="print-info-item"
										v-if="item.color">品名:{{ item.clothes_name + '/' + item.color }}</span>
									<span class="print-info-item" v-else>品名:{{ item.clothes_name }}</span>
									<span class="print-info-item">类型:{{ item.kinds_name }}</span>
									<span class="print-info-item" v-if="item.price">单价:{{ item.price }}</span>
								</div>
								<div class="print-info">
									<span
										class="print-info-item">架号:{{ item.monad_code + (item.split_code || '') }}</span>
									<span
										class="print-info-item">姓名:{{ `${order.take_name}/${order.take_mobile}` }}</span>
								</div>
								<div class="print-info">
									<span class="print-info-item">备注:{{ item.remark }}</span>
								</div>
							</div>
						</div>
					</div>
					<!--  -->
					<div v-for="(item, index) in printList" :key="index" style="display: none">
						<div :id="`page${index + 1}`" :ref="`page${index + 1}`"
							style="margin-top: 10px; padding-left: 10px; clear: both" class="print-page">
							<div class="print-left" style="float: left">
								<div class="print-img">
									<barcode :value="item.bar_code" :width="1.1" :height="35" :fontSize="9"
										fontOptions="Arial" :text="item.bar_code">条形码生成失败</barcode>
								</div>
								<!-- <div class="print-code">{{ item.bar_code }}</div> -->
							</div>
							<div class="print-right" style="float: left; margin-top: 6px">
								<div class="print-info">
									<span class="print-info-item" style="font-size: 12px">
										店名:{{ store.name }}
										<template v-if="item.kinds_status == 1">(奢侈品)</template>
										<template v-if="order.is_urgent > 0">(加急)</template>
										<template v-if="item.pack_price > 0">(包装)</template>
									</span>
								</div>
								<div class="print-info">
									<span class="print-info-item"
										style="display: inline-block; font-size: 12px; margin-right: 10px"
										v-if="item.color">品名:{{ item.clothes_name + '/' + item.color }}</span>
									<span class="print-info-item"
										style="display: inline-block; font-size: 12px; margin-right: 10px"
										v-else>品名:{{ item.clothes_name }}</span>
									<span class="print-info-item"
										style="display: inline-block; font-size: 12px; margin-right: 10px">类型:{{ item.kinds_name }}</span>
									<span class="print-info-item"
										style="display: inline-block; font-size: 12px; margin-right: 10px"
										v-if="item.price">单价:{{ item.price }}</span>
								</div>
								<div class="print-info">
									<span class="print-info-item"
										style="display: inline-block; font-size: 12px; margin-right: 10px">架号:{{ item.monad_code + (item.split_code || '') }}</span>
									<span class="print-info-item"
										style="display: inline-block; font-size: 12px; margin-right: 10px">姓名:{{ `${order.take_name}/${order.take_mobile}` }}</span>
								</div>
								<div class="print-info">
									<div class="print-info-item" style="display: inline-block; font-size: 12px">
										备注:{{ item.remark }}
									</div>
								</div>
							</div>
						</div>
					</div>
					<div class="print-btns">
						<!-- <a-button type="primary" @click="doPrintAndWash">确定打印送洗</a-button> -->
						<!-- <a-button type="primary" v-print="printObj">确定打印送洗(vue-print)</a-button> -->
						<!-- <a-button @click="doPrint()">只打印不送洗</a-button> -->
						<a-button type="primary" @click="lodopPrintWash" v-if="order.send_worker_from != 'jd'">确定打印送洗</a-button>
						<a-button @click="lodopPrint" v-if="order.send_worker_from != 'jd'">只打印不送洗</a-button>
						<!-- <a-button @click="expressOrderShow" v-if="order.send_worker_from == 'jd' && order.express_status != 1">物流下单</a-button> -->
						<a-button @click="printWL" v-if="order.send_worker_from == 'jd' && order.express_status != 1">物流下单</a-button>
						<a-button @click="expressOrderCan" v-if="order.send_worker_from == 'jd' && order.express_status == 1">取消物流订单</a-button>
						<a-button @click="expressOrderPri" v-if="order.send_worker_from == 'jd' && order.express_status == 1">打印物流订单</a-button>
					</div>
				</div>
			</a-card>
		</a-spin>
		<clothesAddForm ref="createModal" @ok="clothesOrderDetail" />
		<express-remark ref='expressRemark' @ok='clothesOrderDetail' />
	</page-header-wrapper>
</template>

<script>
	import {
		clothesOrderDetail,
		clothesWash,
		toExpress,
	} from '@/api/clothes'
	import {
		expressOrderCreate,
		expressOrderCancle,
		expressOrderPrinter
	} from '@/api/jd'
	import orderStatus from '@/mixins/orderStatus'
	import payStatus from '@/mixins/payStatus'
	import clothesStatus from '@/mixins/clothesStatus'
	import {
		getJCP
	} from '@/assets/js/jcp-vue.js'
	import BackButton from '@/components/BackButton'
	import expressRemark from '@/views/clothes/modules/expressRemark'
	import {
		isIE
	} from '@/utils/util'
	import clothesAddForm from './modules/clothesAddForm'
	import getLodop from '@/assets/js/LodopFuncs.js'
	const columns = [{
			title: '衣服名',
			dataIndex: 'clothes_name',
		},
		{
			title: '衣服图片',
			dataIndex: 'img_url',
			scopedSlots: {
				customRender: 'img_url',
			},
		},
		{
			title: '分类名称',
			dataIndex: 'kinds_name',
		},
		{
			title: '是否奢侈品',
			dataIndex: 'kinds_status',
			scopedSlots: {
				customRender: 'kinds_status',
			},
		},
		{
			title: '是否保价',
			dataIndex: 'is_protect_price',
			scopedSlots: {
				customRender: 'is_protect_price',
			},
		},
		{
			title: '条形码',
			dataIndex: 'bar_code',
		},
		{
			title: '货架号',
			dataIndex: 'monad_code',
			customRender(text, record) {
				return text + record.split_code
			},
		},
		{
			title: '是否备注',
			dataIndex: 'is_remark',
			customRender(text, record) {
				return record.is_remark == '1'?'已备注':'未备注'
			},
		},
		{
			title: '状态',
			dataIndex: 'is_take',
			scopedSlots: {
				customRender: 'is_take',
			},
		},
		{
			title: '操作',
			dataIndex: 'action',
			width: '150px',
			scopedSlots: {
				customRender: 'action',
			},
		},
	]

	export default {
		components: {
			BackButton,
			clothesAddForm,
			expressRemark
		},
		mixins: [orderStatus, payStatus, clothesStatus],
		data() {
			return {
				cart: [],
				order: {},
				store: {},
				sign: {},
				columns,
				loading: false,
				manager_type: 1,
				printList: [],
				printObj: {
					id: 'print_container',
					popTitle: '打印',
					extraCss: 'https://www.google.com,https://www.google.com',
					extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
				},
				myDoc: {
					settings: {
						paperName: 'a4', // 纸张名称
						portrait: true, // 纵向
					},
					documents: document, // 打印页面(div)们在本文档中
					copyrights: '家乐洗  http://jialexi.top', // 版权声明必须
				},
				isActvityOrder: false,
				showimg: false,
				lookimg: '',
				express: {}, //京东物流
				remark:'',
				
				printerList:[],
				printName:'',
			}
		},
		computed: {
			title() {
				return this.$route.meta.title
			},
		},
		created() {
			this.clothesOrderDetail()
			const endpoint = 'ws://127.0.0.1:9113'; // WebSocket的地址
			this.socket = new WebSocket(endpoint);
			
			this.socket.addEventListener('message', (e) => {
				// 处理服务器发送的消息
				var json = eval('(' + e.data + ')');
				var content = json.content;
				alert('打印机列表:'+content);
				this.printerList = json.content.split(',');
				this.printerList.forEach((item,index)=>{
					let idx = item.indexOf('Deli');
					if(idx != '-1'){
						this.printName = item;
					}
				})
			});
		},
		methods: {
			// 打印物流
			printWL(record){
				let time = 0;
				let timer = setInterval(()=>{
					var text = "{\"orderType\":\"GET_Printers\",\"pin\":\"用户名\",\"parameters\":{		\"tempUrl\":\"\",		\"printName\":\"\",		\"printData\":\"\"	}}";
					this.socket.send(text);
					time++;
					if(this.printName){
						clearInterval(timer);
						toExpress({
							id: this.order.id
						}).then(res=>{
							if (res.status == '0') {
								if(this.printName){
									res.data.parameters.printName = this.printName;
								}
								this.socket.send(JSON.stringify({
									orderType:res.data.orderType,
									key:res.data.key,
									parameters:res.data.parameters,
								}));
							} else {
								this.$message.error(res.msg);
							}
						})
					}else{
						if(time >= 5){
							clearInterval(timer);
							this.$message.error('请检查打印设备并重试');
						}
					}
				},1000);
			},
			expressOrderShow(){
				const data = {
					id:this.order.id,
					remark: this.remark
				}
				this.$refs.expressRemark.show(data)
			},
			expressOrderPri() {
				var that = this
				this.$confirm({
					title: '提示',
					content: '确认要打印物流订单标签吗?',
					onOk: () => {
						var that = this
						//先调用接口再打印
						expressOrderPrinter({
							id: that.order.id,
						}).then((res) => {
							that.printer(res.data)
						})
					},
				})
			},
			printer(data) {
				console.log(data)
				if(this.socket && this.socket.readyState != 1){
					this.$message.warning('请开启京东打印组件')
					return false;
				}
				this.socket.send(JSON.stringify(data))
				this.$message.warning('打印成功')
				
				// let timer = setInterval(() => {
				// 	console.log(this.socket.readyState)
				// 	//判断是否链接
				// 	if (this.socket.readyState == 1) {
				// 		clearInterval(timer)
				// 		this.socket.send(data)
				// 		this.$message.warning('打印成功')
				// 	}
				// }, 1000)
			},
			expressOrderCan() {
				var that = this
				this.$confirm({
					title: '提示',
					content: '确认要取消物流订单吗?',
					onOk: () => {
						var that = this
						//先调用接口再打印
						expressOrderCancle({
							id: that.order.id,
						}).then((res) => {
							that.$message.warning(res.msg)
							setTimeout(function() {
								that.clothesOrderDetail()
							}, 1500)

						})
					},
				})
			},
			expressOrder() {
				console.log(this.remark)
				return;
				var that = this
				this.$confirm({
					title: '提示',
					content: '确认要创建物流订单吗?',
					onOk: () => {
						var that = this
						//先调用接口再打印
						expressOrderCreate({
							id: that.order.id,
						}).then((res) => {
							that.$message.warning(res.msg)
							setTimeout(function() {
								that.clothesOrderDetail()
							}, 1500)
						})
					},
				})
			},
			getUserCard() {
				let cardShow = []
				if (this.sign.is_vip === 1 && this.sign.is_steward === 1) {
					cardShow.push('V·L')
				} else if (this.sign.is_vip === 1) {
					cardShow.push('V')
				} else if (this.sign.is_steward === 1) {
					cardShow.push('L')
				}
				if (!cardShow.length) cardShow.push('-')
				return cardShow.join(' ')
			},
			handleAdd(readd) {
				this.$refs.createModal.show({
					readd,
				})
			},
			handleSplit(record) {
				this.$router.push({
					name: 'clothesSplit',
					params: {
						id: record.id,
						seal_code: this.order.seal_code,
					},
				})
			},
			getIsActvityOrder() {
				const order = this.order
				if (
					(order.activity_id && order.is_take === 4 && order.status === 1) ||
					(order.activity_id && order.is_take === 6 && order.status === 1)
				) {
					return true
				}
				return false
			},
			clothesOrderDetail() {
				const params = this.$route.query
				this.loading = true
				return clothesOrderDetail(params).then((res) => {
					this.cart = res.data.car
					this.order = res.data.order
					this.store = res.data.store
					this.sign = res.data.sign
					this.manager_type = res.data.manager_type
					this.isActvityOrder = this.getIsActvityOrder()
					if (this.order.express_status == 1) {
						this.express = JSON.parse(this.order.express_msg)
						// console.log(this.express)
					}
					// 将拆分衣物从主衣物里提取出来
					this.printList = res.data.car.reduce((total, current) => {
						const sliceRemark = (remark) => {
							if (remark && remark.length > 22) {
								return remark.slice(0, 22) + '...'
							}
							return remark
						}
						current.remark = sliceRemark(current.remark)
						const splitList = [current]
						if (current.split && current.split.length) {
							splitList.push(
								...current.split.map((splitItem) => {
									return {
										...splitItem,
										remark: sliceRemark(splitItem.remark),
										kinds_name: current.kinds_name,
										clothes_name: `${current.clothes_name}-${splitItem.name}`,
										color: current.color,
									}
								})
							)
						}
						total.push(...splitList)
						return total
					}, [])
					console.log('this.printList: ', this.printList)
					const data = {
						data: res.data.car,
					}
					this.loading = false
					return data
				})
			},
			lodopPrintWash() {
				this.$confirm({
					title: '提示',
					content: '确认要打印并送洗吗?',
					onOk: () => {
						var that = this
						//先调用接口再打印
						clothesWash({
							// seal_code: that.order.seal_code,
							id:this.order.id,
						}).then((res) => {
							const success = that.lodopPrint();
							console.log(success);
							if (success) {
								that.clothesOrderDetail()
							}
						})
					},
				})
			},
			lodopPrint() {
				const refs = document.body.querySelectorAll('.print-page')
				console.log(refs)
				const LODOP = getLodop()
				console.log(LODOP)
				if (!LODOP) {
					return this.$message.warning('Web打印服务CLodop未安装启动,请下载安装')
				}
				let success = true
				for (const key in refs) {
					if (refs[key].innerHTML) {
						const status = this.CreateOneFormPage(refs[key].innerHTML)
						if (!status) {
							this.$message.warning('打印失败,请检查打印机或更换非IE浏览器重试')
							success = false
							break
						}
					}
				}
				return success
			},
			CreateOneFormPage(htmlContent) {
				const LODOP = getLodop()
				LODOP.PRINT_INIT('')
				LODOP.SET_PRINT_PAGESIZE(1, 1055, 200)
				// LODOP.SET_PRINT_MODE("POS_BASEON_PAPER", true);
				LODOP.ADD_PRINT_HTM(0, 0, 1055, 200, htmlContent)
				const isProd = process.env.NODE_ENV === 'production'
				const status = isProd ? LODOP.PRINT() : LODOP.PREVIEW()
				return status
			},
			doPrintAndWash() {
				this.$confirm({
					title: '提示',
					content: '确认要打印并送洗吗?',
					onOk: () => {
						if (isIE()) {
							return clothesWash({
								seal_code: this.order.seal_code,
							}).then(() => {
								var jcp = getJCP()
								jcp.print(this.myDoc, false)
								this.$message.success('操作成功')
							})
						} else {
							this.$message.warning('打印方法不支持当前浏览器,请更改为IE浏览器!')
							return Promise.resolve()
						}
					},
				})
			},
			doPrint(params) {
				var jcp = getJCP()
				// 调用打印方法
				if (params === 'preview') {
					jcp.printPreview(this.myDoc, false) // 不弹出对话框打印
				} else {
					jcp.print(this.myDoc, false) // 不弹出对话框打印
				}
			},
			largeimg(img) {
				this.lookimg = img
				this.showimg = true
			},
		},
	}
</script>

<style lang="less" scoped>
	.table-title-container {
		display: flex;
		align-items: center;
		margin-bottom: 32px;

		.table-title {
			margin: 0;
		}

		.imgs {
			display: flex;
			align-items: center;
			justify-content: flex-start;
			flex: 1;

			img {
				width: 80px;
				height: 80px;
				margin-left: 20px;
			}
		}

		.imgpage {
			width: 100%;
			height: 100%;
			background: rgba(0, 0, 0, 0.3);
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			display: flex;
			align-content: center;
			justify-content: center;
			z-index: 2000;

			img {}
		}
	}

	.print-item-wrap {
		box-shadow: 0px 1px 10px 0px rgba(217, 217, 217, 0.35);
		// border: 1px solid #eeeeee;
		width: 556px;
		&:not(:first-child) {
			margin-top: 10px;
		}
	}

	.print-item {
		background: #ffffff;
		display: flex;
		padding: 18px 20px 16px;
		box-sizing: border-box;

		.print-img {

			// width: 86px;
			// height: 41px;
			img {
				width: 100%;
				height: 100%;
			}
		}

		.print-code {
			margin-top: 8px;
			font-size: 12px;
			text-align: center;
		}

		.print-right {
			flex: 1;
			display: inline-block;
		}

		.print-info {
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			width: 426px;

			.print-info-item {
				font-size: 14px;
				margin-left: 20px;
				// display: inline-block;
			}
		}
	}

	// .print-page {
	//   .print-info {
	//    line-height: 1.2;
	//   }
	// }

	.print-container {
		.print-btns {
			display: flex;
			margin-top: 20px;

			button {
				margin-right: 8px;
			}
		}
	}
</style>